import Vue from 'vue'
import Vuex from 'vuex'
import createLogger from 'vuex/dist/logger'
import createPersistedState from 'vuex-persistedstate'

Vue.use(Vuex)
Vue.config.debug = true

const debug = process.env.NODE_ENV !== 'production'

function handleModels (context) {
  const models = {}
  context.keys().map((key) => {
    const array = key.split('/')
    const fullName = array[array.length - 1]
    // let name = array[array.length-1].slice(0,fullName.length-10)
    const model = context(key).default

    if (!model.namespace) throw new Error('请定义模块' + fullName + '的namespace属性')

    model.namespaced = true
    let name = model.namespace
    models[name] = model
  })
  return models
}

const modelContext = require.context('./modules', true, /.js$/)
const modules = handleModels(modelContext)

export default new Vuex.Store({
  modules: {
    ...modules
  },
  strict: debug,
  plugins: debug ? [createLogger(), createPersistedState()] : [createPersistedState()]
})
